package com.itheima.Practice;

import java.util.ArrayList;
import java.util.Scanner;

public class Method {
    private ArrayList<Student> studentList = new ArrayList<>();
    private Scanner scanner = new Scanner(System.in);

    // 添加学生方法
    public void addStudent() {
        System.out.print("请输入学生学号：");
        String id = scanner.next();
        if (isIdExist(id)) {
            System.out.println("你输入的学号已经被占用,请重新输入");
            return;
        }
        System.out.print("请输入学生姓名：");
        String name = scanner.next();
        System.out.print("请输入学生年龄：");
        int age = scanner.nextInt();
        System.out.print("请输入学生居住地：");
        String address = scanner.next();

        Student student = new Student(id, name, age, address);
        studentList.add(student);
        System.out.println("添加学生成功");
    }

    // 查询学生方法
    public void queryStudent() {
        System.out.println("学号\t\t姓名\t年龄\t居住地");
        for (Student student : studentList) {
            System.out.println(student.getId() + "\t\t" + student.getName() + "\t" + student.getAge() + "岁\t" + student.getAddress());
        }
    }

    // 删除学生方法
    public void deleteStudent() {
        System.out.print("请输入你要删除的学生的学号：");
        String id = scanner.next();
        int index = getIndex(id);
        if (index == -1) {
            System.out.println("该信息不存在，请重新输入！");
            return;
        }
        studentList.remove(index);
        System.out.println("删除学生成功");
    }

    // 修改学生方法
    public void updateStudent() {
        System.out.print("请输入你要修改的学生的学号：");
        String id = scanner.next();
        int index = getIndex(id);
        if (index == -1) {
            System.out.println("该信息不存在，请重新输入！");
            return;
        }
        System.out.print("请输入学生新姓名：");
        String name = scanner.next();
        System.out.print("请输入学生新年龄：");
        int age = scanner.nextInt();
        System.out.print("请输入学生新居住地：");
        String address = scanner.next();

        Student student = new Student(id, name, age, address);
        studentList.set(index, student);
        System.out.println("修改学生成功");
    }

    // 获取学生在集合中的索引
    private int getIndex(String id) {
        for (int i = 0; i < studentList.size(); i++) {
            Student student = studentList.get(i);
            if (student.getId().equals(id)) {
                return i;
            }
        }
        return -1;
    }

    // 判断学号是否存在
    private boolean isIdExist(String id) {
        return getIndex(id) != -1;
    }
}